<template>
  <lay-table :page="page" :columns="columns" :data-source="dataSource" :loading="loading" style="height: 100%;">
    <!-- <template v-slot:toolbar>
      <lay-button size="xs" type="primary" @click="changeAddVisible">新增</lay-button>
    </template> -->
    <template v-slot:operator="{ row }">
      <lay-button size="xs" @click="update(row)" border="green" border-style="dashed">编辑</lay-button>

      <lay-popconfirm :content="row.resource_count === 0 ? '确定要删除吗？' : '不能删除！存在已关联资源!'" position="left"
        @confirm="remove(row)" @cancel="() => layer.msg('操作已取消！', { icon: 3, time: 1000 })">
        <lay-button size="xs" border="red" border-style="dashed" :disabled="row.resource_count !== 0">删除</lay-button>
      </lay-popconfirm>
    </template>
  </lay-table>

  <!-- 新增 ========================================== -->
  <lay-layer v-model="addVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'新增地址'" :btn="addAction">
    <div style="padding: 20px;">
      <lay-form :model="newAddress" ref="addAddressForm">
        <lay-form-item label="省/自治区" prop="province" required>
          <lay-input v-model="newAddress.province"></lay-input>
        </lay-form-item>
        <lay-form-item label="市" prop="city" required>
          <lay-input v-model="newAddress.city"></lay-input>
        </lay-form-item>
        <lay-form-item label="区/县" prop="county" required>
          <lay-input v-model="newAddress.county"></lay-input>
        </lay-form-item>
        <lay-form-item label="乡/镇" prop="town">
          <lay-input v-model="newAddress.town"></lay-input>
        </lay-form-item>
        <lay-form-item label="村" prop="village">
          <lay-input v-model="newAddress.village"></lay-input>
        </lay-form-item>
        <lay-form-item label="详细地址" prop="detail">
          <lay-input v-model="newAddress.detail"></lay-input>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>

  <!-- 修改信息 ========================================== -->
  <lay-layer v-model="updateVisible" :shade="false" :area="['500px', '']" :resize="true" :title="'修改地址'"
    :btn="updateAction">
    <div style="padding: 20px;">
      <lay-form :model="updateAddress" ref="updateAddressForm">
        <lay-form-item label="ID" prop="id">
          <lay-input v-model="updateAddress.id" :disabled="true"></lay-input>
        </lay-form-item>
        <lay-form-item label="省/自治区" prop="province" required>
          <lay-input v-model="updateAddress.province"></lay-input>
        </lay-form-item>
        <lay-form-item label="市" prop="city" required>
          <lay-input v-model="updateAddress.city"></lay-input>
        </lay-form-item>
        <lay-form-item label="区/县" prop="county" required>
          <lay-input v-model="updateAddress.county"></lay-input>
        </lay-form-item>
        <lay-form-item label="乡/镇" prop="town">
          <lay-input v-model="updateAddress.town"></lay-input>
        </lay-form-item>
        <lay-form-item label="村" prop="village">
          <lay-input v-model="updateAddress.village"></lay-input>
        </lay-form-item>
        <lay-form-item label="详细地址" prop="detail">
          <lay-input v-model="updateAddress.detail"></lay-input>
        </lay-form-item>
      </lay-form>
    </div>
  </lay-layer>
</template>

<script setup>
import { ref, reactive, onMounted, h } from 'vue';
import { layer } from '@layui/layui-vue';
import api from '@/api';

const queryForm = ref({
  pageNum: 1,
  pageSize: 20,
  province: ["广西"],
  city: [],
  county: [],
  town: [],
  village: [],
})

const page = reactive({ current: 1, limit: 20, limits: [20, 50, 100, 500], total: 10, layout: ["page", "limits", "prev", "refresh", "count", "next", "skip",] });
// 分页、排序、筛选等参数
const change = (page) => {
  queryForm.value.pageNum = page.current;
  queryForm.value.pageSize = page.limit;
  loading.value = true;
  initDataList();
}
// attach change handler to page prop per layui-vue new API
page.change = change;

const loading = ref(true);

// 获取数据列表
const dataSource = ref([]);
const initDataList = async () => {
  loading.value = true
  await api.post("system/address/search", queryForm.value).then((res) => {
    if (res.code === 200) {
      console.log(res.data);
      loading.value = false
      dataSource.value = res.data || []
      page.total = res.total;
      // if (page.total > 500 && !page.limits.includes(page.total)) {
      //   page.limits.push(page.total);
      // }
      // getSelectList()
    } else {
      layer.msg(res.msg, { icon: 2, time: 5000 });
    }
  })
}


// 新增
const addVisible = ref(false);

const newAddress = reactive({
  province: "广西",
  city: "",
  county: "",
  town: "",
  village: "",
  detail: "",
})
const addAddressForm = ref();

const addAddressHandler = async () => {
  let response = await api.get('/system/address/add', {
    province: newAddress.province,
    city: newAddress.city,
    county: newAddress.county,
    town: newAddress.town,
    village: newAddress.village,
    detail: newAddress.detail
  });

  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    initDataList(); // 刷新地址列表
    addVisible.value = !addVisible.value;
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const addAction = ref([
  {
    text: "添加",
    callback: () => {
      if (addAddressForm.value.validate()) {
        addAddressHandler();
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      addVisible.value = !addVisible.value;
    }
  }
])


// 修改信息
const updateVisible = ref(false);
const updateAddress = reactive({
  id: null,
  province: "",
  city: "",
  county: "",
  town: "",
  village: "",
  detail: "",
})
const updateAddressForm = ref();

async function update(row) {
  console.log('@row:', row.id);
  updateAddress.id = row.id;
  updateAddress.province = row.province;
  updateAddress.city = row.city;
  updateAddress.county = row.county;
  updateAddress.town = row.town;
  updateAddress.village = row.village;
  updateAddress.detail = row.detail;
  updateVisible.value = !updateVisible.value;
}

const updateAddressHandler = async () => {
  let response = await api.get('/system/address/update', {
    id: updateAddress.id,
    province: updateAddress.province,
    city: updateAddress.city,
    county: updateAddress.county,
    town: updateAddress.town,
    village: updateAddress.village,
    detail: updateAddress.detail
  });
  if (response.code === 200) {
    layer.msg(response.msg, { icon: 1, time: 1000 });
    initDataList(); // 刷新地址列表
    updateVisible.value = !updateVisible.value;
  } else {
    layer.msg(response.msg, { icon: 2, time: 2000 });
  }
}

const updateAction = ref([
  {
    text: "保存",
    callback: () => {
      if (updateAddressForm.value.validate()) {
        updateAddressHandler();
      } else {
        layer.msg("请填写完整信息！", { icon: 2, time: 2000 });
        return;
      }
    }
  },
  {
    text: "取消",
    callback: () => {
      layer.msg("操作已取消！", { icon: 3, time: 1000 });
      updateVisible.value = !updateVisible.value;
    }
  }
])


// 删除
async function remove(row) {
  if (row.resource_count !== 0) {
    // layer.msg('不能删除！存在已关联资源!', { icon: 2, time: 2000 });
    return;
  }
  const response = await api.get('/system/address/delete', { id: row.id });
  if (response.code === 200) {
    initDataList(); // 刷新地址列表
    layer.msg(response.msg, { icon: 1, time: 1000 })
  } else {
    layer.msg(response.msg, { icon: 2, time: 1000 })
  }
}


const columns = [
  // { fixed: "left", type: "checkbox", title: "复选" },
  { title: "ID", key: "id", width: "70px", align: 'center', sort: true },
  { title: "省/自治区", key: "province", align: 'center', ellipsisTooltip: true, },
  { title: "市", key: "city", align: 'center', ellipsisTooltip: true, },
  { title: "区/县", key: "county", align: 'center', ellipsisTooltip: true, },
  { title: "乡/镇", key: "town", align: 'center', ellipsisTooltip: true, },
  { title: "村", key: "village", align: 'center', ellipsisTooltip: true, },
  { title: "详细地址", key: "detail", align: 'center', ellipsisTooltip: true, },
  { title: "关联资源数", key: "resource_count", align: 'center', ellipsisTooltip: true, sort: true },
  { title: "操作", key: "operator", width: "100px", align: 'center', customSlot: "operator", fixed: "right", ignoreExport: true }
]

onMounted(() => {
  initDataList()
});
</script>

<style scoped>
.layui-card-body {
  padding: 5px !important;
}
</style>